package com.example.servlet;

import com.example.model.CartDAO;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@WebServlet("/cart")
public class CartServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action = request.getParameter("action");
        HttpSession session = request.getSession();
        Integer userId = (Integer) session.getAttribute("userId");
        if (userId == null) {
            response.sendRedirect("login.jsp");
            return;
        }
        if ("add".equals(action)) {
            int bookId = Integer.parseInt(request.getParameter("bookId"));
            int quantity = Integer.parseInt(request.getParameter("quantity"));
            CartDAO.addToCart(userId, bookId, quantity);
            response.sendRedirect("cart.jsp");
        } else if ("update".equals(action)) {
            int bookId = Integer.parseInt(request.getParameter("bookId"));
            int quantity = Integer.parseInt(request.getParameter("quantity"));
            CartDAO.updateQuantity(userId, bookId, quantity);
            response.sendRedirect("cart.jsp");
        } else if ("delete".equals(action)) {
            int bookId = Integer.parseInt(request.getParameter("bookId"));
            CartDAO.deleteItem(userId, bookId);
            response.sendRedirect("cart.jsp");
        } else if ("clear".equals(action)) {
            CartDAO.clearCart(userId);
            response.sendRedirect("cart.jsp");
        } else if ("checkout".equals(action)) {
            // 结账逻辑可扩展
            CartDAO.clearCart(userId);
            response.sendRedirect("cart.jsp?success=1");
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        Integer userId = (Integer) session.getAttribute("userId");
        if (userId == null) {
            response.sendRedirect("login.jsp");
            return;
        }
        List<Map<String, Object>> cartList = CartDAO.getCartByUser(userId);
        request.setAttribute("cartList", cartList);
        request.getRequestDispatcher("cart.jsp").forward(request, response);
    }
} 